﻿<%@ WebHandler Language="C#" Class="ContainerStepPlanFinishRateDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;

/**
 * Description: 排产完成率看板(生产部)
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2022.6.16
 */

public class ContainerStepPlanFinishRateDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetail":
                        r = getDetail(jObject);//明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getExportExcel":
                        getExportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getData(JObject jObject)
    {
        string sql = @"
SELECT t.plandate,COUNT(t.workflowstepname) planqty,SUM(DECODE(t.status,'已完工',1,0)) finishqty,
       ROUND(SUM(DECODE(t.status,'已完工',1,0)) / COUNT(t.workflowstepname) ,4) * 100 finishrate
FROM (
  SELECT f.factoryname,cci.fromworkcentername,cci.mfgordername,cci.containername,ws.sequence,ws.workflowstepname,
         csp.plannedfinishdate plandate,t.checkDate,DECODE(t.checkDate,NULL,'未完工','已完工') status
  FROM containerstepplan csp
  LEFT JOIN containercurrentinfo cci ON cci.containerid = csp.containerid
  LEFT JOIN mes_factory_mapping f ON f.factoryid = cci.originalfactoryid
  LEFT JOIN workflowstep ws ON ws.workflowstepid = csp.workflowstepid
  LEFT JOIN (
      SELECT csr.containerid,csr.workflowstepid,MAX(csr.checkdate) checkDate
      FROM containersteprecord csr
      GROUP BY csr.containerid,csr.workflowstepid 
  ) t ON t.containerid = cci.containerid AND t.workflowstepid = ws.workflowstepid
  LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
  LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
  LEFT JOIN containerstepnoship csn ON csn.containerid = cci.containerid AND csn.workflowstepid = csp.workflowstepid AND csn.noship = 2 AND csn.isuse = 0
  LEFT JOIN containercommidetail cm ON cm.containerid = csp.containerid AND cm.workflowstepid = csp.workflowstepid AND cm.isuse = 0
  WHERE csp.plantype = 1 AND cci.containerstatus = 1
        AND ((cci.isinstore = 1 AND cci.workflowid <> ws.workflowid) OR (cci.isinstore = 0 AND cci.workflowid = ws.workflowid))
        AND NVL(s.controlcode,'LY01') <> 'LY05' AND cm.containercommidetailid IS NULL AND csn.containerstepnoshipid IS NULL ";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }
        else
        {
            sql += " AND f.factorycode IN ('600','601','607','608','609') ";
        }

        //日期范围
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            sql += string.Format(" AND TRUNC(csp.plannedfinishdate) >= TO_DATE('{0}','yyyy-mm-dd') ", arr[0].ToString());
            sql += string.Format(" AND TRUNC(csp.plannedfinishdate) <= TO_DATE('{0}','yyyy-mm-dd') ", arr[1].ToString());
        }

        sql += @"
) t
GROUP BY t.plandate
ORDER BY t.plandate";
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    string getDetailSql(JObject jObject)
    {
        string sql = @"
SELECT f.factoryname,cci.mfgordername,cci.containername,ws.sequence,ws.workflowstepname,
       csp.plannedfinishdate plandate,t.checkdate,DECODE(t.checkdate,NULL,'未完工','已完工') status
FROM containerstepplan csp
LEFT JOIN containercurrentinfo cci ON cci.containerid = csp.containerid
LEFT JOIN mes_factory_mapping f ON f.factoryid = cci.originalfactoryid
LEFT JOIN workflowstep ws ON ws.workflowstepid = csp.workflowstepid
LEFT JOIN (
    SELECT csr.containerid,csr.workflowstepid,MAX(csr.checkdate) checkDate
    FROM containersteprecord csr
    GROUP BY csr.containerid,csr.workflowstepid 
) t ON t.containerid = cci.containerid AND t.workflowstepid = ws.workflowstepid
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
LEFT JOIN containerstepnoship csn ON csn.containerid = cci.containerid AND csn.workflowstepid = csp.workflowstepid AND csn.noship = 2 AND csn.isuse = 0
LEFT JOIN containercommidetail cm ON cm.containerid = csp.containerid AND cm.workflowstepid = csp.workflowstepid AND cm.isuse = 0
WHERE csp.plantype = 1 AND cci.containerstatus = 1
      AND ((cci.isinstore = 1 AND cci.workflowid <> ws.workflowid) OR (cci.isinstore = 0 AND cci.workflowid = ws.workflowid))
      AND NVL(s.controlcode,'LY01') <> 'LY05' AND cm.containercommidetailid IS NULL AND csn.containerstepnoshipid IS NULL ";
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            var date = jObject["selectdate"].ToString().Split(' ')[0];
            sql += string.Format(" AND csp.plannedfinishdate = to_date('{0}','yyyy-MM-dd') ", date);
        }

        if (jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryid = '{0}'", jObject["factoryid"].ToString());
        }
        else
        {
            sql += " AND f.factorycode IN ('600','601','607','608','609') ";
        }

        sql += @"
ORDER BY f.factoryname,cci.containername,ws.sequence";
        return sql;
    }

    Result getDetail(JObject jObject)
    {
        string sql = getDetailSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    void getExportExcel(JObject jObject)
    {
        string sql = getDetailSql(jObject);
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dt.Columns["factoryname"].Caption = "主制分厂";
        dt.Columns["mfgordername"].Caption = "订单号";
        dt.Columns["containername"].Caption = "流水卡号";
        dt.Columns["sequence"].Caption = "工序号";
        dt.Columns["workflowstepname"].Caption = "工序名称";
        dt.Columns["plandate"].Caption = "计划完成时间";
        dt.Columns["checkdate"].Caption = "完成时间";
        dt.Columns["status"].Caption = "状态";
        ExportHelper.ExportExcel(dt, jObject["title"].ToString());
    }
}